﻿using System;
using System.Data;
using System.Collections;
using System.Text;
using System.Configuration;

namespace BizElements.Core
{
    #region Documentation.
    /// <summary>
    /// Determines whether or not a given expression is <b>null</b>.
    /// </summary>
    /// <remarks>IsNullPredicate cannot be created by using its constructor. 
    /// Use <see cref="PredicateFactory"/> to create predicates.
    /// <seealso cref="SearchCondition"/></remarks>
    /// <example>
    /// The following example selects all employees who report to no one (ReportsTo field is <b>null</b>).
    /// <code>
    /// public DataTable SelectEmployeesWhoReportToNoOne()
    /// {
    /// 	EmployeesMeta employees = new EmployeesMeta();
    /// 	SelectStatement select = new SelectStatement(employees);
    /// 	select.Where.Add(PredicateFactory.IsNull(employees.ReportsTo));
    /// 	return select.Execute();
    /// }
    /// </code>
    /// </example>
    #endregion
    [Serializable]
    public sealed class IsNullPredicate : PredicateBase
    {
        #region IS NULL.

        /// <summary>
        /// Creates a new IS NULL predicate.
        /// </summary>
        /// <param name="item">Items/expression.</param>
        /// <param name="negate">Specifies whether the predicate is negated (IS NOT NULL).</param>
        internal IsNullPredicate(PredicateItem item, bool negate)
        {
            PredicateItems = new PredicateItem[] { item };
            Negate = negate;
        }

        /// <summary>
        /// Renders predicate as SQL statement.
        /// </summary>
        /// <param name="dbms">Target DBMS.</param>
        /// <param name="output">StringBuilder to which SQL is appended.</param>
        /// <param name="parameters">SQL parameter collection to which the object's and its children's
        /// parameters are added. After the rendering is done the collection contains all parameters with unique names.</param>
        public override void Render(DbmsType dbms, StringBuilder output, DbParameterCollection parameters)
        {
            output.Append("(");
            PredicateItems[0].Render(dbms, output, parameters);

            if (Negate)
                output.Append(" IS NOT NULL");
            else
                output.Append(" IS NULL");
            output.Append(")");
        }

        #endregion
    }
}
